import { throttle, event_bus } from '@/utils'
import loading from '@/assets/loading.svg'

let imgs = []

// 滚动条滚动时，处理图片懒加载
event_bus.$on('main_scroll', throttle(handle_imgs, 50))

function handle_img(img) {
    img.dom.src = loading
    const rect = img.dom.getBoundingClientRect()
    // 当图片在视口范围内时，处理
    if (rect.top > -rect.height * 0.3 && rect.top < innerHeight) {
        const target_img = new Image()
        target_img.onload = () => {
            img.dom.src = img.src
        }
        target_img.src = img.src
        // 处理过后，删除当前元素
        imgs = imgs.filter(item => item.src !== img.src)
    }
}

function handle_imgs() {
    for (const img of imgs) {
        handle_img(img)
    }
}

export default {
    inserted(el, binding) {
        const img = {
            dom: el,
            src: binding.value
        }
        imgs.push(img)
        handle_img(img)
    },
    unbind(el, binding) {
        imgs = imgs.filter(item => item.src !== binding.value)
    }
}

